<template>
  <div class="all-box">
    <div class="all-box-left">
      <div class="a-card is-always-shadow left-box left-box-normal" style="width: calc(22.5%)">
        <a-card>
          <div class="answerCard">
            <span style="font-size: 18px;margin-left: 5px">答题卡</span>
          </div>
          <a-divider />
          <div class="card-box">
            <div class="item" v-for="(item,index) in answerCardList" :key="index"
                 @click="selectQuestion(item)">
              <div :class="cardItemClass(item)">{{ item }}</div>
            </div>
          </div>
        </a-card>
      </div>
    </div>
    <div class="all-box-center">
      <div class="a-card content-card is-always-shadow"
           style="width: calc(75%);height: calc(100vh - 65px);position: absolute;overflow: auto">
        <a-card>
          <div class="list-box">
            <div class="list-qu" style="width: 100%">
              <div style="display:flex;justify-content: space-between;align-items: center">
                <a-alert style="padding-left: 10px;width: 100px" :message="cardItem.type_dictText"
                         type="info"
                         show-icon />
                <a-button type="primary" danger @click="submit">提交练习</a-button>
              </div>
              <div class="qu-box">
                <div class="qu-item">
                  <div class="num">
                    {{ cardItem.questionIndex }}
                  </div>
                  <div class="content">
                    <div v-html="cardItem.content"></div>
                  </div>
                </div>
                <div class="qu-answer" v-if="cardItem.questionType == 5">
                  <div class="item" v-for="(answerItem,index2) in cardItem.answerList"
                       :key="index2">
                    <div class="tag">{{ answerItem.tag }}</div>
                    <div class="content">
                      <a-input v-model:value="answerItem.contentTmp" @blur="cacheBlankAnswer()"
                               :disabled="!!cardItem?.answered" />
                    </div>
                  </div>
                </div>
                <div class="qu-answer" v-else>
                  <div :class="answerItemClass(index2)"
                       v-for="(answerItem,index2) in cardItem.answerList"
                       :key="index2"
                       @click="selectAnswer(index2,cardItem.questionType,answerItem.id)">
                    <div class="tag">{{ answerItem.tag }}</div>
                    <div class="content">
                      {{ answerItem.content }}

                      <img
                        :src="getFileAccessHttpUrl(answerItem.contentImage)"
                        :title="answerItem.contentImage"
                        style="width: 150px; height: 100px; object-fit: cover;"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div>
            <template v-if="cardItem.questionType == 2 ||cardItem.questionType == 5">
              <a-button type="primary" color="error" @click="confirmAnswer">确认答案</a-button>
            </template>
          </div>
          <div style="margin-top: 20px">
            <a-button type="primary" v-if="cardItem.questionIndex != 1"
                      style="width: 100px;margin-right: 30px"
                      :icon="h(LeftOutlined)"
                      @click="handPrevious()">上一题
            </a-button>
            <a-button type="primary" danger
                      v-if="cardItem.questionIndex < pagination.total"
                      :icon="h(RightOutlined)"
                      @click="handNext()"
                      style="width: 100px;">下一题
            </a-button>
          </div>

          <template
            v-if="currentAnswerIndex?.length > 0 && (cardItem.questionType ==1 ||cardItem.questionType ==3)">
            <div class="as-box">
              <div class="right-line">
                <a-alert message="答对了" type="success" show-icon v-if="cardItem.isRight" />
                <a-alert message="答错了" type="error" show-icon v-else />
              </div>
              <div v-if="!cardItem.isRight">
                <div style="font-weight: 700">参考答案：</div>
                <span style="margin-left: 20px">{{ currentRightAnswer }}</span>
              </div>
              <template v-if="cardItem.analysis && cardItem.analysis.length>0">
                <div style="font-weight: 700">解析：</div>
                <span v-html="cardItem.analysis" style="margin-left: 20px"></span>
              </template>
            </div>
          </template>
          <template
            v-if="isConfirmAnswer && (cardItem.questionType ==2 || cardItem.questionType ==5)">
            <div class="as-box">
              <div class="right-line">
                <a-alert message="答对了" type="success" show-icon v-if="cardItem.isRight" />
                <a-alert message="答错了" type="error" show-icon v-else />
              </div>
              <div v-if="!cardItem.isRight">
                <div style="font-weight: 700">参考答案：</div>
                <span style="margin-left: 20px">{{ currentRightAnswer }}</span>
              </div>
              <template v-if="cardItem.analysis && cardItem.analysis.length>0">
                <div style="font-weight: 700">解析：</div>
                <span v-html="cardItem.analysis" style="margin-left: 20px"></span>
              </template>
              <template v-if="cardItem.analysis && cardItem.analysis.length>0">
                <div>解析：</div>
                <span v-html="cardItem.analysis"></span>
              </template>
            </div>
          </template>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { h, reactive, ref, watch } from "vue";
import { apiListQuestionByMode, apiSubmitPractice } from "@/api/practice";
import { useRoute, useRouter } from "vue-router";
import { useMessage } from "@/hooks/web/useMessage";
import { LeftOutlined, RightOutlined } from "@ant-design/icons-vue";
import {getFileAccessHttpUrl} from "@/utils/compUtils";

const route = useRoute();
const repositoryId = route.params?.id ?? -1;
const mode = route.query?.mode;
const questionType = route.query?.questionType;

const router = useRouter();
const cardItem = ref<any>({});
//试题信息
const message = ref<any>();

//当前题的答案索引
const currentAnswerIndex = ref<any>([]);
const endTime = ref<any>();
//所有试题的答案
const questionAnswers = ref<any>([]);
//本题答案
const answers = ref<any>([]);
const { createMessage } = useMessage();
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
  pages: 0
});

const loading = ref<boolean>(false);
const form = ref<any>([]);
const answerCardList = ref<any>([]);

//是否答对
const answerIsRight = ref<boolean>(false);

//当前试题正确答案
const currentRightAnswer = ref<any>();
//当前试题正确答案索引
const currentRightIndexArray = ref<any>([]);

//多选和填空是否进行答案确认
const isConfirmAnswer = ref<boolean>(false);

//初始化试题和答题卡
initFormData();

//缓存填空题答案
function cacheBlankAnswer() {
  if (cardItem.value?.answered) {
    return;
  }
  if (checkBlankIsAnswered()) { //作答了，则替换原来的值（存在的话）
    console.log("回答了，则替换原来的值");
    //先删除
    questionAnswers.value.forEach((item, index1) => {
      if (item.index == cardItem.value.questionIndex) {
        questionAnswers.value.splice(index1, 1);
      }
    });
    let arr: any = [];
    cardItem.value.answerList.forEach((item) => {
      if (item.contentTmp && item.contentTmp.length > 0 && item.contentTmp.trim().length > 0) {
        arr.push({ tag: item.tag, content: item.contentTmp.trim() });
      }
    });
    questionAnswers.value.push({
      index: cardItem.value.questionIndex,
      blankAnswer: JSON.stringify(arr)
    });
  } else { //不作答，删掉原来的答案
    console.log("不作答，删掉原来的答案");
    questionAnswers.value.forEach((item, index1) => {
      if (item.index == cardItem.value.questionIndex) {
        questionAnswers.value.splice(index1, 1);
      }
    });
  }
  console.log(questionAnswers.value);
}

//检查当前填空题是否已经回答
function checkBlankIsAnswered() {
  if (cardItem.value.questionType == 5) {
    for (let item of cardItem.value.answerList) {
      if (item.contentTmp && item.contentTmp.length > 0 && item.contentTmp.trim().length > 0) {
        return true;
      }
    }
    return false;
  }
}

//初始化试题和选项卡
async function initFormData() {
  //清空当前题索引
  currentAnswerIndex.value = [];
  //初始化清空已选答案
  questionAnswers.value = [];

  await list(1, 10);

  // 获得第一题内容
  getQuestion(1);
}

async function list(pageNo: any, pageSize: any) {
  loading.value = true;
  if (pageNo) pagination.pageNo = pageNo;
  if (pageSize) pagination.pageSize = pageSize;
  let params = {
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize,
    repositoryId: repositoryId,
    mode: mode,
    questionType: questionType
  };
  try {
    const data: any = await apiListQuestionByMode(params);
    if (data.result?.records?.length > 0) {
      data.result.records.forEach((item: any) => {
        form.value.push(item);
        item.questionType = item.type;
        item.questionIndex = form.value.length;
      });
    }
    answerCardList.value = [];
    form.value.forEach((item) => {
      answerCardList.value.push(item.questionIndex);
    });
    pagination.total = data.result.total;
    pagination.pages = data.result.pages;
  } finally {
    loading.value = false;
  }
}

async function loadNext() {
  pagination.pageNo++;
  console.log("触底加载,当前页：" + pagination.pageNo);
  await list(pagination.pageNo, pagination.pageSize);
}


//获取当前试题
function getQuestion(index) {
  if (form.value?.length > 0) {
    const obj = form.value.filter((val, i) => i + 1 == index)[0];
    if (obj) {
      cardItem.value = obj;
    }
  }
  isConfirmAnswer.value = false;
  if (cardItem.value?.questionType == 2 || cardItem.value?.questionType == 5) {
    if (cardItem.value?.answered) {
      isConfirmAnswer.value = true;
    }
  }

  //获取试题正确答案
  getRightAnswer();
  if (cardItem.value.questionType == 2) {
    //获取当前正确答案索引
    getRightIndexArray();
  }
}

// 答题卡样式
function cardItemClass(index) {
  const tmpList = form.value.filter(val => val.questionIndex == index);
  if (tmpList && tmpList.length > 0) {
    if (tmpList[0].isRight != null) {
      if (tmpList[0].isRight) {
        return "num success";
      } else {
        return "num error";
      }
    } else {
      return "num info";
    }
  }
}

function answerItemClass(index) {
  let answerIndex = currentAnswerIndex.value.filter(val => val == index);
  if (answerIndex && answerIndex.length > 0) {
    return "item active";
  } else {
    return "item";
  }
}

//选择试题
function selectQuestion(numItem) {
  clearAnswer();
  currentAnswerIndex.value = [];
  answers.value = [];
  getQuestion(numItem);
  fillAnswer(numItem);
}

/**
 * 下一题
 */
async function handNext() {
  clearAnswer();
  currentAnswerIndex.value = [];
  answers.value = [];
  const index = cardItem.value.questionIndex + 1;
  if (index > form.value?.length && pagination.pageNo < pagination.pages) {
    await loadNext();
  }
  getQuestion(index);
  fillAnswer(index);
}

/**
 * 上一题
 */
function handPrevious() {
  clearAnswer();
  currentAnswerIndex.value = [];
  answers.value = [];
  const index = cardItem.value.questionIndex - 1;
  getQuestion(index);
  fillAnswer(index);
}


//填充答案
function fillAnswer(index) {
  const list = form.value.filter(val => val.questionIndex == index);
  if (list && list.length > 0) {
    const questionItem = list[0];
    const tmpList = questionAnswers.value.filter(val => val.index == index);
    if (tmpList && tmpList.length > 0) {
      //单选，多选，判断才去勾选答案样式
      if (questionItem.questionType == 1 || questionItem.questionType == 2 || questionItem.questionType == 3) {
        currentAnswerIndex.value = tmpList[0].answerIndex;
        answers.value = tmpList[0].answers;
      } else if (questionItem.questionType == 5) {//填空题回填答案到输入框
        let answer = tmpList[0].blankAnswer;
        let blankAnswerArr = JSON.parse(answer);
        cardItem.value.answerList.forEach((item) => {
          const answerList = blankAnswerArr.filter(val => val.tag == item.tag);
          if (answerList && answerList.length > 0) {
            item.contentTmp = answerList[0].content;
          }
        });
      }
    }
  }
}


//选择或者取消答案
function selectAnswer(index, questionType, answerId) {
  if (cardItem.value.answered) {
    return;
  }
  const tmpList = questionAnswers.value.filter(val => val.index == cardItem.value.questionIndex);
  if (tmpList && tmpList.length > 0) {
    if (tmpList[0].answers && tmpList[0].answers.length > 0) {
      const t1 = tmpList[0].answers.filter(val => val == answerId);
      if (t1 && t1.length > 0) {
        //如果是已经勾选的答案，则删除-------取消
        canceled(tmpList, index, questionType, answerId);
      } else {
        //选择答案
        selected(index, questionType, answerId);
      }
    }
  } else {
    //选择答案
    selected(index, questionType, answerId);
  }
}


//取消答案
function canceled(tmpList, index, questionType, answerId) {
  console.log("取消答案");
  //删除勾选样式
  currentAnswerIndex.value = currentAnswerIndex.value.filter(val => val != index);
  tmpList[0].answerIndex = currentAnswerIndex.value.slice();

  //删除答案
  answers.value = answers.value.filter(val => val != answerId);
  tmpList[0].answers = answers.value.slice();
  if (tmpList[0].answers.length == 0) {//如果没有答案则清除index
    questionAnswers.value = questionAnswers.value.filter(val => val.index != cardItem.value.questionIndex);
  }
  console.log(questionAnswers.value);
}


// 选择答案
function selected(index, questionType, answerId) {
  console.log("选择答案");
  //-------选择答案
  if (questionType == 1 || questionType == 3) {
    currentAnswerIndex.value = [];
    answers.value = [];
  }
  currentAnswerIndex.value.push(index);
  answers.value.push(answerId);

  //先删除对应试题的答案
  questionAnswers.value.forEach((item, index1) => {
    if (item.index == cardItem.value.questionIndex) {
      questionAnswers.value.splice(index1, 1);
    }
  });
  questionAnswers.value.push({
    index: cardItem.value.questionIndex,
    answers: answers.value.slice(), //复制数组
    answerIndex: currentAnswerIndex.value.slice()
  });
  console.log(questionAnswers.value);
}

//提交
async function submit() {
  const questionList = form.value.filter(val => val?.answered);
  if (!questionList || questionList.length == 0) {
    createMessage.info("请先作答试题再提交训练，填空题和多选题需确认答案！");
    return;
  }
  let params = {
    repositoryId: repositoryId,
    mode: mode,
    questionType: questionType,
    questionList: questionList,
    answers: questionAnswers.value
  };
  const data: any = await apiSubmitPractice(params);
  await router.push({ path: `/practice/userpracticeresult/` + data.result });
}

watch(
  () => currentAnswerIndex.value,
  () => {
    if (cardItem.value.questionType == 1 || cardItem.value.questionType == 3) {//单选和判断
      if (currentAnswerIndex.value?.length > 0) {
        const rightIndex: any = cardItem.value?.answerList.findIndex((val: any) => !!val.isRight);
        if (currentAnswerIndex.value.includes(rightIndex)) {
          answerIsRight.value = true;
        } else {
          answerIsRight.value = false;
        }
        cardItem.value.answered = true;//已答
        cardItem.value.isRight = answerIsRight.value;
      } else {
        cardItem.value.answered = false;
      }
    }
  }
);

//多选和填空需要手动确认答案
function confirmAnswer() {
  isConfirmAnswer.value = false;
  if (cardItem.value.questionType == 2) {//多选题
    if (currentAnswerIndex.value?.length == 0) {
      answerIsRight.value = false;
    } else {
      if (currentAnswerIndex.value.length != currentRightIndexArray.value.length) { //答案个数不一致，判为错误
        answerIsRight.value = false;
      } else {
        const tmpList = currentRightIndexArray.value.filter((val: any) => !currentAnswerIndex.value.includes(val));
        if (!tmpList || tmpList?.length == 0) {
          answerIsRight.value = true;
        } else {
          answerIsRight.value = false;
        }
      }
    }
  } else if (cardItem.value.questionType == 5) {//填空题
    let userAnswerList: any = [];
    cardItem.value.answerList.forEach((item: any) => {
      if (item.contentTmp?.trim()) {//过滤无效答案
        userAnswerList.push({ tag: item.tag, content: item.contentTmp });
      }
    });
    let resultArray: any = [];
    let answerList = cardItem.value.answerList.slice();
    for (let userAnswer of userAnswerList) {
      if (!!cardItem.value?.answerOrder) {
        compareByOrder(cardItem.value.answerList, userAnswer, resultArray);
      } else {
        compareByNoOrder(answerList, userAnswer, resultArray);
      }
    }
    if (resultArray?.length > 0) {
      cardItem.value.blankAnswer = JSON.stringify(resultArray);
      if (resultArray.length != cardItem.value.answerList.length) { //如果有空没作答
        answerIsRight.value = false;
      } else {
        const obj = resultArray.filter(d => !d.isRight)[0];
        if (!obj) {//全部答对了
          answerIsRight.value = true;
        } else {//有错误答案
          answerIsRight.value = false;
        }
      }
    }
  }
  cardItem.value.isRight = answerIsRight.value;
  isConfirmAnswer.value = true;
  cardItem.value.answered = true;
}

function clearAnswer() {
  if (!cardItem.value?.answered) {
    //删除缓存答案
    questionAnswers.value.forEach((item, index1) => {
      if (item.index == cardItem.value.questionIndex) {
        questionAnswers.value.splice(index1, 1);
      }
    });
    //填空题回答的内容置空
    if (cardItem.value?.questionType == 5) {
      cardItem.value.answerList.forEach((item) => {
        item.contentTmp = "";
      });
    }
  }
}

/**
 * 获取当前题正确答案
 */
function getRightAnswer() {
  if (cardItem.value?.questionType == 1 || cardItem.value?.questionType == 2 || cardItem.value?.questionType == 3) {
    const rightArray: any = cardItem.value?.answerList.filter(val => !!val.isRight);
    let tmpList: any = [];
    if (cardItem.value.questionType == 3) {
      tmpList = rightArray.map(v => {
        return v.content;
      });
    } else {
      tmpList = rightArray.map(v => {
        return v.tag;
      });
    }
    currentRightAnswer.value = tmpList.join(",");
  } else if (cardItem.value?.questionType == 5) {
    const tmpList: any = cardItem.value?.answerList.map(v => {
      return v.content;
    });
    currentRightAnswer.value = tmpList.join("；");
  }
}

/**
 * 获取当前正确答案索引
 */
function getRightIndexArray() {
  currentRightIndexArray.value = [];
  cardItem.value?.answerList.filter((val, index) => {
    if (!!val.isRight) {
      currentRightIndexArray.value.push(index);
    }
  });
}


//严格按照顺序对比-填空题
function compareByOrder(answerList, userAnswer, resultArray) {
  const tmp = answerList.filter(a => a.tag == userAnswer.tag)[0];
  if (tmp) {
    const answerArray = tmp.content.split("||");
    if (answerArray.length > 0) {
      if (answerArray.includes(userAnswer.content.trim())) {
        resultArray.push({
          tag: userAnswer.tag,
          content: userAnswer.content.trim(),
          isRight: true
        });
      } else {
        resultArray.push({
          tag: userAnswer.tag,
          content: userAnswer.content.trim(),
          isRight: false
        });
      }
    }
  }
}

//不按顺序对比，只要答案在其中一个选项中找到符合的就行
function compareByNoOrder(answerList, userAnswer, resultArray) {
  let isTrue = false;
  for (let index = 0; index < answerList.length; index++) {
    const answerArray = answerList[index].content.split("||");
    if (answerArray.length > 0) {
      if (answerArray.includes(userAnswer.content.trim())) {
        resultArray.push({
          tag: userAnswer.tag,
          content: userAnswer.content.trim(),
          isRight: true
        });
        isTrue = true;
        answerList.splice(index, 1);
        break;
      }
    }
  }
  if (!isTrue) {
    resultArray.push({ tag: userAnswer.tag, content: userAnswer.content.trim(), isRight: false });
  }
}
</script>

<style scoped>
.all-box {
  position:relative;
  height:100vh;
  padding: 10px 10px;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  flex-direction: row;
}

.all-box-left {
  -webkit-box-flex: 0;
  flex: 0 0 22.5%;
}

.left-box-normal {
}

.left-box {
  height: calc(100vh - 65px);
  position: absolute;
  overflow: auto;
  clear: both;
}

.a-card.is-always-shadow {
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.a-card {
  border-radius: 4px;
  border: 1px solid #e6ebf5;
  background-color: #FFFFFF;
  color: #303133;
  transition: 0.3s;
}

.ant-card-bordered {
  border: none;
}

>>> .ant-card-body {
  padding: 20px;
}

.typeClass {
  font-size: 14px;
  font-weight: 700;
}

.group-card-body {
  line-height: 22px;
  font-size: 14px;
}

.numberClass {
  color: #448efc;
  font-style: italic;
}

.card-box {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  margin-left: -5px;
  margin-top: 10px;
  width: 100%;
}

.card-box .item {
  width: 30px;
  height: 35px;
  background: #eee;
  border-radius: 2px;
  font-size: 12px;
  -webkit-box-align: center;
  align-items: center;
  cursor: pointer;
  margin: 5px 5px 10px 5px;
}

.card-box .item .num {
  text-align: center;
  padding: 3px;
  height: 20px;
  line-height: 14px !important;
}

.card-box .item .info {
  border-radius: 2px;
  background: #1890ff;
  color: #fff !important;
}

.card-box .item .error {
  border-radius: 2px;
  background: red;
  color: #fff !important;
}

.card-box .item .success {
  border-radius: 2px;
  background: #00bb00;
  color: #fff !important;
}

.all-box-center {
  flex-grow: 1;
  margin-left: 20px;
}

.content-card {
  margin-bottom: 20px;
  line-height: 28px;
}

.a-card.is-always-shadow {
  -webkit-box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.list-box {
  display: flex;
  padding-bottom: 20px;
  border-bottom: #eee 3px dotted;
  margin-bottom: 20px;
}

.qu-box {
  margin-top: 10px;
  margin-bottom: 20px;
}

.qu-item {
  display: flex;
  margin-bottom: 20px;
}

.qu-item > .num {
  display: inline-block;
  background: url("../../assets/img/pick.png") no-repeat 100% 100%;
  background-size: contain;
  height: 35px;
  width: 35px;
  line-height: 30px;
  color: #fff;
  font-size: 14px;
  text-align: center;
  margin-right: 15px;
  flex-shrink: 0;
}

.qu-item > .content {
  flex-grow: 1;
  align-items: flex-start;
}

.qu-answer > .item {
  display: flex;
  border: #eee 1px solid;
  border-radius: 5px;
  line-height: 20px;
  margin: 15px 0px 15px 0px;
  padding: 10px;
  cursor: pointer;
  font-size: 14px;
}

.qu-answer > .item > .tag {
  width: 10px;
  font-weight: 700;
  color: #0a84ff;
  display: flex;
  -webkit-box-align: center;
  align-items: center;
}

.qu-answer > .item > .content {
  -webkit-box-flex: 1;
  flex-grow: 1;
  padding-left: 10px;
}

.qu-answer > .active {
  background-color: rgba(0, 204, 85, 0.5);
}

:deep(span.xe-blanknumber) {
  width: 4em;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin: 0 2px;
  border-bottom: black solid 1px;
}

.answerCard {
  display: flex;
  justify-content: center;
  align-items: center
}

.as-box {
  border: #eee 1px solid;
  border-radius: 5px;
  line-height: 26px;
  margin-top: 20px;
  padding: 10px;
  font-size: 14px;
  color: #555;
  background: #fcfcfc;
}

.right-line {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  font-weight: 700;
  font-size: 16px;
  margin-bottom: 10px;
}

.right-line .right {
  color: #03DD6D;
  font-size: 22px;
  margin-right: 10px;
}
</style>
